package cn.rulian.base.main.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rulian.base.auth.bo.Resource;
import cn.rulian.base.auth.bo.ResourceType;
import cn.rulian.base.auth.bo.Role;
import cn.rulian.base.auth.bo.User;
import cn.rulian.base.auth.dao.ResourceDao;
import cn.rulian.base.auth.pojo.Sys;
import cn.rulian.base.auth.pojo.SysConfig;
import cn.rulian.base.auth.service.UserService;
import cn.rulian.base.common.dto.Message;
import cn.rulian.base.common.dto.UserInfo;
import cn.rulian.base.common.property.BusinessProperty;
import cn.rulian.base.common.util.MD5Util;
import cn.rulian.base.common.util.xx;

/**
 * 登录Controller
 */

//@RestController
@Controller
public class LoginController
{
	@Autowired
	UserService userService;

	@Autowired
	private ResourceDao resourceDao;

	@Autowired
	BusinessProperty pro; //业务参数
	
	private final Logger log = LoggerFactory.getLogger(getClass());
	
	/**
	 * 默认系统--登录界面
	 */
	@RequestMapping({"/", "/rulian"})
	public String toLogin(Model model)
	{
		Sys sys = SysConfig.SYS_DEF;
		model.addAttribute("sys", sys);
		return "login/"+sys.getLoginCode()+"/login";
	}
	
	/**
	 * 车辆外出管理系统--登录界面
	 */
	@RequestMapping("/car")
	public String toLogin1(Model model)
	{
		Sys sys = SysConfig.SYS_CAR;
		if(!sys.isEnabled())
		{
			return "base/main/404";
		}
		model.addAttribute("sys", sys);
		return "login/"+sys.getLoginCode()+"/login";
	}

	/**
	 * 登出
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session, String sysCode) 
	{
		UserInfo userInfo = (UserInfo)session.getAttribute("userInfo");
		if(userInfo != null)
		{
			log.info("用户退出登录。用户名：{} ",userInfo.getUser().getUsername());
			session.removeAttribute("userInfo");
		}
		if(SysConfig.SYS_DEF.getCode().equals(sysCode))
		{
			return "redirect:/";
		}
		return "redirect:/" + sysCode;
	}

	/**
	 * 登录验证
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Message login(String user_name, String password, String sysCode, HttpSession session)
	{
		
		Message rm = new Message();
		
		User user = userService.findUserByUserNameAndPwd(user_name, MD5Util.MD5(password));
		if(user==null)
		{
			rm.setCode(Message._ERROR);
			rm.setMsg("用户名或密码错误！");
			return rm;
		}
		
		Boolean enabled = user.getEnabled();
		if(enabled != null && !enabled)
		{
			rm.setCode(Message._ERROR);
			rm.setMsg("用户不可用，请与管理员联系！");
			return rm;
		}
		
		//构建用户信息
		UserInfo userInfo = new UserInfo();
		userInfo.setUser(user);
		user.getOrgan().getName(); //加载机构
		List<Role> roleList = user.getRoleList();
		if(!xx.isEmpty(roleList))
		{
			//构造角色ID列表
			List<Long> ids = new ArrayList<>(); //拥有的角色ID列表
			for(Role role:roleList)
			{
				ids.add(role.getId());
			}
			userInfo.setRoleIds(ids);
			
			//构造按钮权限码串
			StringBuilder buttonAuthCode = new StringBuilder(","); //拥有的按钮权限码
			List<Resource> allButtonList = resourceDao.findByResourceType_codeOrderByOrderNum(ResourceType.BUTTON_CODE);
			if(!xx.isEmpty(allButtonList))
			{
				for(Role role:roleList)
				{//遍历角色
					ids.add(role.getId());
					List<Resource> reList = role.getResourceList();
					if(!xx.isEmpty(reList))
					{
						for(Resource re:reList)
						{//遍历角色拥有的资源
							for(Resource one:allButtonList)
							{
								if(re.getId().longValue() == one.getId().longValue())
								{//过滤掉不是按钮的资源
									buttonAuthCode.append(re.getAuthCode()+",");
									break;
								}
							}
						}
					}
				}
			}
			userInfo.setButtonAuthCode(buttonAuthCode.toString());
		}
		
		//加入系统信息
		Sys sys = SysConfig.map.get(sysCode);
		if(sys == null)
		{
			rm.setCode(Message._ERROR);
			rm.setMsg("系统唯一编号错误！");
			return rm;
		}
		userInfo.setSys(sys);
		
		session.setAttribute("userInfo", userInfo);
		
		log.info("用户登录。用户名：{} ,密码：{}",user_name,password);
		rm.setMsg("登录成功");
		return rm;
	}

	/**
	 * 无权限
	 */
	@RequestMapping("/noAccess")
	public String noAccess()
	{
		return "base/main/noAccess";
	}

	/**
	 * 会话超时
	 */
	@RequestMapping("/noSession")
	public String noSession(Model model)
	{
		model.addAttribute("defSysCode", SysConfig.SYS_DEF.getCode()); //默认系统编码
		return "base/main/noSession";
	}

	/**
	 * 系统错误
	 */
	@RequestMapping("/four")
	public String four()
	{
		return "base/main/four";
	}
	
	
}
